package com.cloud.zhimao.common.config.aspect;

import com.cloud.zhimao.common.base.aspect.BaseAspect;
import com.cloud.zhimao.common.config.annotation.Authority;
import com.cloud.zhimao.common.config.exception.CloudException;
import com.cloud.zhimao.common.utils.ServiceUtil;
import com.cloud.zhimao.common.utils.ShiroUtil;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
import com.cloud.zhimao.common.config.exception.Assert;

/**
 * @author Long
 */
@Aspect
@Slf4j
@Component
public class AuthorityAspect extends BaseAspect {
    boolean aspect = false;

    /**
     * 设置操作日志切入点 记录操作日志 在注解的位置切入代码
     */
    @Pointcut("@annotation(com.cloud.zhimao.common.config.annotation.Authority)")
    public void aspect() {
        // 该方法无方法体,主要为了让同类中其他方法使用此切入点
    }

    @Override
    @Before("aspect()")
    public void doBefore(JoinPoint jp) {
//        if (true) return;
        String msg = "未登录，您当前无权操作";
        Authority authority = null;
        try {
            authority = jp.getThis().getClass().getAnnotation(Authority.class);
            if (ServiceUtil.isNull(authority)) {
                return;
            }
        }catch (Exception e){
            throw new CloudException(msg, "权限控制拦截：" + msg);
        }

        if (!authority.auth()){
            return;
        }
        aspect = true;
        Long userId;
        try {
            userId = ShiroUtil.getProfile().getId();
        }catch (Exception e){
            throw new CloudException(msg, "权限控制拦截：" + msg);
        }

        if (authority.root()){
            Assert.isTrue(ServiceUtil.equal(1, userId) , authority.desc());
        } else {
            Assert.notNull(userId, authority.desc());
        }
    }

    @Override
    @After("aspect()")
    public void doAfter(JoinPoint jp) {
        if (aspect) {
            log.warn("========================权限控制触发========================");
        }
    }
}
